<template>
  <div>
    <el-dialog
      title="添加取药订单"
      :visible.sync="show"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
      @close="cancel"
    >
      <div>
        <div>
          <h3>机柜药品列表</h3>
          <el-form
            ref="editForm"
            :model="editForm"
            :rules="rules"
            inline
            label-width="80px"
          >
            <el-form-item label="机构名称" prop="institutionId">
              <el-select
                v-model="editForm.institutionId"
                placeholder="请选择机构名称"
                filterable
                clearable
                @change="getStoreList"
              >
                <el-option
                  v-for="item in institutionList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="门店名称" prop="storeId">
              <el-select
                v-model="editForm.storeId"
                placeholder="请选择门店名称"
                filterable
                clearable
                @change="getCabinetList"
              >
                <el-option
                  v-for="item in formStoreList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="柜机名称" prop="cabinetId">
              <el-select
                v-model="editForm.cabinetId"
                placeholder="请选择柜机名称"
                filterable
                clearable
                @change="changeCabinet"
              >
                <el-option
                  v-for="item in formCabinetList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="条码/药品" prop="keyword">
              <el-input
                v-model="editForm.keyword"
                placeholder="请输入条码/药品名称"
                maxlength="30"
                clearable
                @keyup.enter.native="getMedicineList"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="getMedicineList"
              >
                搜索
              </el-button>
            </el-form-item>
          </el-form>
          <el-table :data="medicineList" border max-height="300">
            <el-table-column label="序号" type="index" width="80" align="center" />
            <el-table-column label="药品名称" align="center" prop="medicineName" />
            <el-table-column label="条码" align="center" prop="barCode" />
            <el-table-column label="生产厂家" align="center" prop="manufacturer" />
            <el-table-column label="品种" align="center" width="100">
              <template slot-scope="{ row }">
                <dict-tag :options="mc_medicine_variety_type" :value="row.variety" />
              </template>
            </el-table-column>
            <el-table-column
              label="库存数量"
              align="center"
              prop="inventory"
              width="100"
            />
            <el-table-column label="取出数量" align="center" width="100">
              <template slot-scope="{ row }">
                <el-input-number
                  v-model="row.orderQuantity"
                  :min="0"
                  :max="row.inventory"
                  step-strictly
                  size="mini"
                  :controls="false"
                />
              </template>
            </el-table-column>
            <el-table-column label="添加" align="center" width="100">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  round
                  title="添加药品"
                  icon="el-icon-plus"
                  @click="handleAddMedicine(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="editForm.subOrderList && editForm.subOrderList.length > 0">
          <h3>已选药品</h3>
          <el-table :data="editForm.subOrderList" border max-height="300">
            <el-table-column label="序号" type="index" width="80" align="center" />
            <el-table-column label="药品名称" align="center" prop="medicineName" />
            <el-table-column label="条码" align="center" prop="barCode" />
            <el-table-column label="生产厂家" align="center" prop="manufacturer" />
            <el-table-column label="品种" align="center" width="100">
              <template slot-scope="{ row }">
                <dict-tag :options="mc_medicine_variety_type" :value="row.variety" />
              </template>
            </el-table-column>
            <el-table-column
              label="数量"
              align="center"
              prop="orderQuantity"
              width="100"
            />
            <el-table-column label="移除" align="center" width="100">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  round
                  title="移除药品"
                  icon="el-icon-minus"
                  @click="handleMinusMedicine(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          :disabled="!editForm.subOrderList || editForm.subOrderList.length === 0"
          type="primary"
          @click="submitForm"
        >
          确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { inventoryMedicineList } from "@/api/mc/inventory";
import { addOrder } from "@/api/mc/order";
import { listInstitution } from "@/api/mc/institution";
import { listStore } from "@/api/mc/store";
import { listCabinet } from "@/api/mc/cabinet";
export default {
  name: "UserForm",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    mc_medicine_variety_type: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    show: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
  },
  data() {
    return {
      // 表单参数
      editForm: {
        id: null,
        institutionId: null, // 机构ID
        storeId: null, // 门店ID
        cabinetId: null, // 柜机ID
        subOrderList: [],
      },
      // 表单校验
      rules: {
        institutionId: [{ required: true, message: "机构ID不能为空", trigger: "blur" }],
        storeId: [{ required: true, message: "门店名称不能为空", trigger: "blur" }],
        cabinetId: [{ required: true, message: "柜机名称不能为空", trigger: "blur" }],
      },
      institutionList: [], // 机构列表
      formStoreList: [], // 表单门店列表
      formCabinetList: [], // 表单柜机列表
      medicineList: [], // 药品列表
    };
  },
  watch: {
    value(val) {
      if (val) {
        this.reset();
        this.getInstitutionList();
      }
    },
  },
  methods: {
    /** 查询药品信息列表 */
    getMedicineList() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          inventoryMedicineList({
            pageNum: 1,
            pageSize: 100000,
            cabinetId: this.editForm.cabinetId,
            storeId: this.editForm.storeId,
            keyword: this.editForm.keyword,
          }).then((res) => {
            let list = res.rows.map((i) => {
              let list = this.editForm.subOrderList || [];
              let row = list.find((j) => j.medicineId === i.medicineId);
              return {
                ...i,
                inventory: row ? i.inventory - row.orderQuantity : i.inventory,
                orderQuantity: 0,
              };
            });
            this.medicineList = list;
          });
        }
      });
    },
    // 获取机构列表
    getInstitutionList() {
      listInstitution({ pageNum: 1, pageSize: 1000 }).then((res) => {
        this.institutionList = res.rows;
      });
    },
    // 获取门店列表
    getStoreList() {
      this.editForm.storeId = null;
      this.editForm.cabinetId = null;
      this.medicineList = [];
      this.editForm.subOrderList = [];
      listStore({
        pageNum: 1,
        pageSize: 1000,
        institutionId: this.editForm.institutionId,
      }).then((res) => {
        this.formStoreList = res.rows;
      });
    },
    // 获取柜机列表
    getCabinetList() {
      this.editForm.cabinetId = null;
      this.medicineList = [];
      this.editForm.subOrderList = [];
      listCabinet({ pageNum: 1, pageSize: 1000, storeId: this.editForm.storeId }).then(
        (res) => {
          this.formCabinetList = res.rows;
        }
      );
    },
    // 切换柜机
    changeCabinet() {
      this.editForm.subOrderList = [];
      this.getMedicineList();
    },
    // 新增药品
    handleAddMedicine(row) {
      if (row.orderQuantity == 0) {
        this.$message.error("请输入正确的数量");
        return;
      }
      if (row.inventory < row.orderQuantity) {
        this.$message.error("库存不足");
        return;
      }
      this.editForm.subOrderList.push({ ...row, cabinetId: this.editForm.cabinetId });
      row.inventory = row.inventory - row.orderQuantity;
      row.orderQuantity = 0;
      this.$forceUpdate();
    },
    // 删除药品
    handleMinusMedicine(row) {
      let index = this.medicineList.findIndex((i) => i.id === row.id);
      if (index !== -1) {
        this.medicineList[index].inventory =
          this.medicineList[index].inventory + row.orderQuantity;
        this.$forceUpdate();
      }
      this.editForm.subOrderList = this.editForm.subOrderList.filter(
        (i) => i.id !== row.id
      );
    },
    // 取消按钮
    cancel() {
      this.show = false;
      this.formStoreList = [];
      this.formCabinetList = [];
      this.medicineList = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.editForm = {
        id: null,
        institutionId: null, // 机构ID
        storeId: null, // 门店ID
        cabinetId: null, // 柜机ID
        subOrderList: [],
      };
      this.resetForm("editForm");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          let data = {
            id: this.editForm.id,
            institutionId: this.editForm.institutionId, // 机构ID
            storeId: this.editForm.storeId, // 门店ID
            subOrderList: this.editForm.subOrderList.map((i) => {
              return {
                cabinetId: i.cabinetId,
                medicineId: i.id,
                orderQuantity: i.orderQuantity,
                barCode: i.barCode,
              };
            }),
          };
          addOrder(data).then((res) => {
            this.show = false;
            this.$modal
              .confirm(`新增成功，是否前往订单管理查看？`)
              .then(() => {
                this.$router.push({ path: "/order/order" });
              })
              .catch(() => {});
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-input-number--mini {
  width: 70px;
}
</style>
